/**
 * @description:
 * @Author: wuzhenbin
 * @CreateTime: 2025-02-07
 */
public class leetcode_42 {
    public static void main(String[] args) {
        int[] height1 = {0,1,0,2,1,0,1,3,2,1,2,1};
        int[] height2 = {4,2,0,3,2,5};
        System.out.println(trap(height1)); // 输出：6
        System.out.println(trap(height2)); // 输出：9
    }

    public static  int trap(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }
        int left = 0;
        int right = height.length-1;
        int maxLeft = height[0];
        int maxRight = height[height.length-1];
        int res = 0;
        while(left<right){
            if(height[left]<height[right]){
                if(height[left]>maxLeft){
                    maxLeft = height[left];
                } else  {
                    if(Math.min(maxLeft,maxRight) -height[left]>0){

                        res += Math.min(maxLeft,maxRight) -height[left];
                    }
                }
                left ++;
                if(height[left]>maxLeft){
                    maxLeft = height[left];
                }
            }
            else {
                if(height[right]>maxRight){
                    maxRight = height[right];
                } else {
                    if(Math.min(maxLeft,maxRight) -height[right] >0){
                        res += Math.min(maxLeft,maxRight) -height[right];
                    }
                }
                right --;
                if(height[right]>maxRight){
                    maxRight = height[right];
                }
            }


        }

        return res;
    }

}
